home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c++
- Subject: Re: Error?
- Date: Mon, 08 Jan 1996 02:03:04 GMT
- Organization: Netcom
- Message-ID: <30f075e8.169549440@nntp.ix.netcom.com>
- References: <4cpaov$241@news.rrz.uni-koeln.de>
- NNTP-Posting-Host: ix-dc14-13.ix.netcom.com
- X-NETCOM-Date: Sun Jan 07 6:02:44 PM PST 1996
- X-Newsreader: Forte Agent .99c/16.141
-
- a2867001@smail.rrz.Uni-Koeln.DE (Lars Kaderali) wrote:
-
- |>Hey folks! Need some help - I tried the following program in c++ on
- an
- |>ibm pc:
- |>
- |>=======================================
- |>
- |>//test
- |>#include <iostream.h>
- |>float a,b;
- |>main()
- |>{
- |> a=-1.0; b=0.1;
- |> while (a<1.1)
- |> {
- |> cout<<a<<endl;
- |> a+=b;
- |> }
- |>}
- |>
- |>=======================================
- |>
- |>which returns:
- |>
- |>-1
- |>-0.9
- |>-0.8
- |>-0.7
- |>-0.6
- |>-0.5
- |>-0.4
- |>-0.3
- |>-0.2
- |>-0.1
- |>(so far as expected, but then:)
- |>7.450581e-08 < ==== ??????????????
- |>0.1
- |>0.2
- |>0.3
- |>0.4
- |>0.5
- |>0.6
- |>0.7
- |>0.8
- |>0.9
- |>1
- |>
- |>How come this 7.450581e-08 happens instead of 0.0 ?????
-
- Welcome to the world of binary floating point. On most machines
- floating point numbers are stored in binary. In binary 0.1 cannot be
- expressed exactly with a finite number of digits. The computer does
- the best it can, but actually uses a number that's just close.
-
- This can cause other anomolies. In some cases your loop may go one
- step further or less than you expect.
-
- Using double will make the numbers more accurate, but still not exact
- and the same kind of think will happen. Here, the number printed
- where you expect 0 will be smaller, but probably still not 0.
-
- Michael M Rubenstein
-